<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...')
{
	$strlen = strlen($string);
	if ($strlen <= $length) return $string;
	$string = str_replace(array(' ', '&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵', ' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if (strtolower(CHARSET) == 'utf-8') {
		$length = intval($length - strlen($dot) - $length / 3);
		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {
			$t = ord($string[$n]);
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n++;
				$noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t <= 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n++;
			}
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&', ' ', '"', "'", '“', '”', '—', '<', '>', '·', '…', '∵');
		$replace_arr = array('&amp;', '&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;', ' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut . $dot;
}

/**
 * 生成缩略图函数
 * @param  $imgurl 图片路径
 * @param  $width  缩略图宽度
 * @param  $height 缩略图高度
 * @param  $autocut 是否自动裁剪 默认裁剪，当高度或宽度有一个数值为0是，自动关闭
 * @param  $smallpic 无图片是默认图片路径
 */
function thumb($imgurl, $width = 100, $height = 100, $autocut = 1, $smallpic = 'nopic.png')
{
	if (empty($imgurl)) return APP_URL . "/public/" . $smallpic;
	if (!extension_loaded('gd') || strpos($imgurl, '://')) {
		$imgurl = str_replace(APP_URL, '', $imgurl);
	}
	$imgpath = str_replace('/upload/', ROOT_PATH . 'upload/', $imgurl);
	if (!file_exists($imgpath) || $imgpath == ROOT_PATH . 'upload/') return APP_URL . "/public/" . $smallpic;
	list($width_t, $height_t, $type, $attr) = getimagesize($imgpath);
	if ($width >= $width_t || $height >= $height_t) return $imgurl;
	$newimgurl = dirname($imgpath) . '/thumb_' . $width . '_' . $height . '_' . basename($imgpath);
	if (file_exists($newimgurl)) return str_replace(ROOT_PATH . 'upload/', '/upload/', $newimgurl);

	$image = \think\Image::open($imgpath);
	if ($autocut) {
		//将图片裁剪为400x400并保存为corp.jpg
		$isok = $image->thumb($width, $height, 3)->save($newimgurl);
		//$isok = $image->crop($width, $height)->save($newimgurl);
	} else {
		// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
		$isok = $image->thumb($width, $height)->save($newimgurl);
	}
	return $isok ? str_replace(ROOT_PATH . 'upload/', '/upload/', $newimgurl) : $imgurl;
}

/**
 *时间格式处理
 *x<60分钟，显示x分钟之前；1<=x<24，显示x小时之前；24小时<=x<3天，显示x天；x>=3，显示3天
 */
function timeformat($datetime)
{
	$time = SYS_TIME - $datetime;
	if ($time < 60) {
		$showtime = $time . "秒前";
	} else if ($time < 3600 && $time >= 60) {
		$showtime = ceil($time / 60) . "分钟之前";
	} else if ($time >= 3600 && $time < 24 * 3600) {
		$showtime = ceil($time / 60 / 60) . "小时之前";
	} else {
		$showtime = date("Y-m-d H:i", $datetime);
	}
	// else if($time >= 24*3600 && $time < 30*24*3600){
	// 	$showtime = ceil($time / 60 / 60 / 24)."天之前";
	// }
	// else if($time >= 30*24*3600 && $time < 12*30*24*3600){
	// 	$showtime = ceil($time / 60 / 60 / 24/30)."个月之前";
	// }
	return $showtime;
}
/**
 *时间格式处理
 *x<60分钟，显示x分钟之前；1<=x<24，显示x小时之前；x>=24小时，显示1991-01-01 00:00:00
 */
function timeshow($datetime)
{
	$time = SYS_TIME - $datetime;
	if ($time < 60) {
		$showtime = $time . "秒前";
	} else if ($time < 3600 && $time >= 60) {
		$showtime = ceil($time / 60) . "分钟之前";
	} else if ($time >= 3600 && $time < 24 * 3600) {
		$showtime = ceil($time / 60 / 60) . "小时之前";
	} else if ($time >= 24 * 3600) {
		$showtime = date("Y-m-d H:i:s", $datetime);
	}
	return $showtime;
}
/**
 * [time_show description]
 * @param  [int] $time 数字
 * @param  [int] $isms 是否是毫秒
 * @return char       时间
 */
function time_show($time, $isms)
{
	if ($isms) {
		$a = substr($time, -3);
	}
	$time = substr($time, 0, -3);
	if ($time < 60) {
		$showtime =  '00:00:' . str_pad($time, 2, 0, STR_PAD_LEFT);
	} else if ($time < 3600 && $time >= 60) {
		$showtime = '00:' . str_pad(floor($time / 60), 2, 0, STR_PAD_LEFT) . ':' . str_pad($time % 60, 2, 0, STR_PAD_LEFT);
	} else if ($time >= 3600 && $time < 24 * 3600) {
		$showtime = str_pad(floor($time / 3600), 2, 0, STR_PAD_LEFT) . ':' . str_pad(floor(($time % 3600) / 60), 2, 0, STR_PAD_LEFT) . ':' . str_pad($time % 60, 2, 0, STR_PAD_LEFT);
	} else {
		return false;
	}
	$showtime = $isms ? $showtime . '.' . $a : $showtime;
	return $showtime;
}
function msectime()
{
	list($tmp1, $tmp2) = explode(' ', microtime());
	return (float) sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
}

/**
 * 将字符串转换为数组
 *
 * @param	string	$data	字符串
 * @return	array	返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data)
{
	if ($data == '') return array();
	$data = new_stripslashes($data);
	@eval("\$array = $data;");
	return $array;
}
/**
 * 将数组转换为字符串
 *
 * @param	array	$data		数组
 * @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
 * @return	string	返回字符串，如果，data为空，则返回空
 */
function array2string($data, $isformdata = 1)
{
	if ($data == '') return '';
	if ($isformdata) $data = new_stripslashes($data);
	return addslashes(var_export($data, TRUE));
}
/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_addslashes($string)
{
	if (!is_array($string)) return addslashes($string);
	foreach ($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_stripslashes($string)
{
	if (!is_array($string)) return stripslashes($string);
	foreach ($string as $key => $val) $string[$key] = new_stripslashes($val);
	return $string;
}

/**
 * 返回经htmlspecialchars处理过的字符串或数组
 * @param $obj 需要处理的字符串或数组
 * @return mixed
 */
function new_html_special_chars($string)
{
	if (!is_array($string)) return htmlspecialchars($string);
	foreach ($string as $key => $val) $string[$key] = new_html_special_chars($val);
	return $string;
}
/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string)
{
	$string = str_replace('%20', '', $string);
	$string = str_replace('%27', '', $string);
	$string = str_replace('%2527', '', $string);
	$string = str_replace('*', '', $string);
	$string = str_replace('"', '&quot;', $string);
	$string = str_replace("'", '', $string);
	$string = str_replace('"', '', $string);
	$string = str_replace(';', '', $string);
	$string = str_replace('<', '&lt;', $string);
	$string = str_replace('>', '&gt;', $string);
	$string = str_replace("{", '', $string);
	$string = str_replace('}', '', $string);
	$string = str_replace('\\', '', $string);
	return $string;
}
/**
 * 生成随机字符串
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_randomstr($lenth = 6)
{
	return random($lenth, '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}
function del_enter($str = '')
{
	return $str == '' ? '/' : str_replace(array("\r", "\n", "\r\n"), array("", "", ""), $str);
}
/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789')
{
	$hash = '';
	$max = strlen($chars) - 1;
	for ($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
	// 创建Tree
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] = &$list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId =  $data[$pid];
			if ($root == $parentId) {
				$tree[] = &$list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent = &$refer[$parentId];
					$parent[$child][] = &$list[$key];
				}
			}
		}
	}
	return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
{
	if (is_array($tree)) {
		foreach ($tree as $key => $value) {
			$reffer = $value;
			if (isset($reffer[$child])) {
				unset($reffer[$child]);
				tree_to_list($value[$child], $child, $order, $list);
			}
			$list[] = $reffer;
		}
		$list = list_sort_by($list, $order, $sortby = 'asc');
	}
	return $list;
}
/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
	if (is_array($list)) {
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
			$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': // 正向排序
				asort($refer);
				break;
			case 'desc': // 逆向排序
				arsort($refer);
				break;
			case 'nat': // 自然排序
				natcasesort($refer);
				break;
		}
		foreach ($refer as $key => $val)
			$resultSet[] = &$list[$key];
		return $resultSet;
	}
	return false;
}
/**
 * rsa加密方法
 * 公钥负责加密，私钥负责解密
 * 私钥负责签名，公钥负责验证
 * @param  [string] $data [原始数据]
 * @param  [string] $key  [秘钥]
 * @param  [int] $type [加密类型 1=公钥 2=私钥]
 * @return [string]       [加密后的数据]
 */
function rsa_encode($data)
{
	$fp = fopen(config('rsa.mypub'), "r"); //对方的公钥文件路径
	$key_data = fread($fp, 8192);
	fclose($fp);

	$encrypted = "";
	openssl_public_encrypt($data, $encrypted, $key_data); //公钥加密
	$encrypted = base64_encode($encrypted);
	return $encrypted;
}
/**
 * rsa解密方法
 * 
 * @param  [string]  $data [加密字符串]
 * @param  [string]  $key  [密钥位置]
 * @param  integer $type [密钥类型]
 * @return [string]        [解密字符]
 */
function rsa_decode($data)
{
	$fp = fopen(config('rsa.priv'), "r"); //我的的私钥文件路径
	$key_data = fread($fp, 8192);
	fclose($fp);

	$decrypted = '';
	openssl_private_decrypt(base64_decode($data), $decrypted, $key_data); //私钥解密
	return $decrypted;
}
/**
 * rsa签名方法
 * @param  [string] $data [原始数据]
 * @param  [string] $key  [秘钥]
 * @return [type]       [签名数据]
 */
function rsa_sign($data)
{
	$fp = fopen(config('rsa.priv'), "r"); //我的私钥文件路径
	$key_data = fread($fp, 8192);
	fclose($fp);

	openssl_sign($data, $sign, $key_data);
	openssl_free_key(openssl_pkey_get_private($key_data));
	$sign = base64_encode($sign); //最终的签名	

	return $sign;
}
/**
 * 验证签名
 * @param  [string] $sign         [签名字符]
 * @param  [string] $original_str [明文字符]
 * @param  [string] $key          [私钥名称]
 * @return [bool]               [验证状态]
 */
function rsa_check_sign($sign, $original_str)
{
	$fp = fopen(config('rsa.mypub'), "r"); //我的公钥
	$key_data = fread($fp, 8192);
	fclose($fp);

	$sign = htmlspecialchars_decode($sign);
	$original_str = htmlspecialchars_decode($original_str);

	$sign = base64_decode($sign); //密文
	return (bool) openssl_verify($original_str, $sign, $key_data); //验证
}
function get_model_func()
{
	$varArray = func_get_args();
	$model = $varArray[0];
	$action = $varArray[1];
	unset($varArray[0]);
	unset($varArray[1]);
	$model = ucwords($model);
	$model_class = model($model);
	return call_user_func_array(array($model_class, $action), $varArray);
}
/**
 * 通过CURL发送HTTP请求
 * @param string $url  //请求URL
 * @param array $postFields //请求参数 
 * @return mixed
 */
function curlPost($url, $data)
{
	$data = is_array($data) && $needjason ? json_encode($data) : $data;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_TIMEOUT, 20);
	$response = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if (curl_errno($ch)) {
		$response =  false;
	}
	curl_close($ch);
	return $response;
}

/** 通过CURL发送GET请求 */
function curlGet($url, $data = [], $timeout = 20)
{
	if ($url == "" || $timeout <= 0) {
		return false;
	}
	if ($data && is_array($data)) {
		$url .= strpos($url, '?') === false ? '?' . http_build_query($data) : '&' . http_build_query($data);
	}
	$con = curl_init((string) $url);
	curl_setopt($con, CURLOPT_HEADER, false);
	curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($con, CURLOPT_TIMEOUT, (int) $timeout);
	return curl_exec($con);
}


//加密用户名
function encrypt($str)
{
	$len = mb_strlen($str, 'utf-8');
	if ($len > 6) {
		$str1 = mb_substr($str, 0, 3, 'utf-8');
		$str2 = mb_substr($str, $len - 4, 4, 'utf-8');
	} else {
		$str1 = mb_substr($str, 0, 1, 'utf-8');
		$str2 = mb_substr($str, $len - 1, 1, 'utf-8');
	}

	return $str1 . '****' . $str2;
}
function check_token($data, $key)
{
	$sign = $data['sign'];
	unset($data['sign']);
	ksort($data);
	$string = '';
	foreach ($data as $k => $v) {
		$string .= $v;
	}
	$string .= $key;
	$md5sign = md5($string);
	if ($md5sign == $sign) {
		return true;
	}
	return false;
}
// function setAppUrl($url, $target = 'self', $callbackTag = 'callback_1488956498800'){
// 	if(is_mobile())
// 		return "http://coco3g-app/gotopage?url=".urlencode($url)."&target=".$target."&callbackTag=".$callbackTag;
// 	else 
// 		return $url;
// }
function open_new_window($newtag, $ordersn = '', $callbackTag = 'callback_1488956498800')
{
	$url = "http://coco3g-app/open_new_window?newtag=" . $newtag . "&callbackTag=" . $callbackTag;
	if ($ordersn) {
		$url .= "&ordersn=" . $ordersn;
	}
	return $url;
}
function setAppUrls($url, $rightBtn = [], $target = 'self', $callbackTag = 'callback_1488956498800')
{
	if (is_mobile()) {
		$url = "https://coco3g-app/gotopage?url=" . urlencode(APP_URL . $url) . "&target=" . $target . "&callbackTag=" . $callbackTag;
		if (!empty($rightBtn)) {
			$rightBtn = json_encode($rightBtn);
			$url .= "&rightBtn=" . $rightBtn;
		}
	}
	return $url;
}
function tabUrl($tab, $title, $rightBtn = [], $callbackTag = 'callback_1488956498800')
{
	$url = "http://coco3g-app/open_tabview?callbackTag=" . $callbackTag;
	$tab = json_encode($tab);
	$url .= "&content=" . $tab . "&title=" . $title;
	if (!empty($rightBtn)) {
		$rightBtn = json_encode($rightBtn);
		$url .= "&rightBtn=" . $rightBtn;
	}
	return $url;
}
/**
 * 禁止下拉
 * @param  string $url         链接
 * @param  string $target      self:当前页打开，blank:新窗口打开
 * @param  string $callbackTag 回调
 * @return string              url
 */
function ban_refresh($url, $target = 'self', $callbackTag = 'callback_1488956498800')
{
	if (DEVICE == 'android') {
		$url = "http://coco3g-app/ban_refresh?url=" . urlencode(APP_URL . $url) . "&target=" . $target . "&callbackTag=" . $callbackTag;
	} else {
		$url = APP_URL . $url;
	}
	return $url;
}
function appShare($url, $title, $content, $thumb, $callbackTag = 'callback_1488956498800', $type = 1)
{
	if (is_mobile()) {
		$url = "http://coco3g-app/share?url=" . APP_URL . $url . "&title=" . $title . "&content=" . $content . "&thumb=" . $thumb . "&type=" . $type . "&callbackTag=" . $callbackTag;
	}
	return $url;
}
function get_pages($model, $where = [], $whereOr = [])
{
	$db = model($model);
	$count = $db->where($where)->whereOr($whereOr)->count();
	return ceil($count / 20);
}
function get_map($data = [], $wheredata = [])
{
	if (empty($data) && empty($wheredata)) return [];
	$wheredata = $wheredata ? $wheredata : [];
	$where = [];
	if ($data) {
		$fieldset = explode(",", $data['fieldset']);
		foreach ($fieldset as $v) {
			$varr = explode("-", $v);
			$varname = $varr[0];
			$value = '';
			if (strpos($varname, '|')) {
				$varname = explode('|', $varname);
				foreach ($varname as $v) {
					$value[] = $data[$v];
				}
			} else {
				$value = $data[$varname];
			}
			$fieldarr = $varr[1];
			$method = isset($varr[2]) ? $varr[2] : 'eq';
			if (!$value) {
				continue;
			}
			switch ($method) {
				case 'like':
					$where[$fieldarr] = ['like', "%$value%"];
					break;
				case 'gt':
					$where[$fieldarr] = ['gt', $value];
					break;
				case 'lt':
					$where[$fieldarr] = ['lt', $value];
					break;
				case 'between':
					if (!$value[0] && !$value[1]) {
						break;
					} elseif (!$value[0] && $value[1]) {
						$where[$fieldarr] = ['elt', $value[1]];
						break;
					} elseif ($value[0] && !$value[1]) {
						$where[$fieldarr] = ['egt', $value[0]];
						break;
					} else {
						$where[$fieldarr] = ['between', $value];
						break;
					}

				case 'betweentime':
					$mintime = strtotime($value . '00:00:00');
					$maxtime = strtotime($value . '23:59:59');
					$where[$fieldarr] = ['between', [$mintime, $maxtime]];
					break;
				default:
					$where[$fieldarr] = $value;
			}
		}
	}
	return array_merge($where, $wheredata);
}
function get_or($data = [])
{
	if (empty($data) || !isset($data['otherModel'])) return [];
	$whereOr = [];
	if ($data['otherModel']) {
		$otherModel = explode(",", $data['otherModel']);
		foreach ($otherModel as $v) {
			$where = [];
			$varr = explode("-", $v);
			$varname = $varr[0];
			$model = $varr[1];
			$fieldarr = $varr[2];
			$key = $varr[3];
			$tokey = $varr[4];
			$method = isset($varr[5]) ? $varr[5] : "=";
			$value = $data[$varname];
			switch ($method) {
				case 'like':
					$where[$fieldarr] = ['like', "%$value%"];
					break;
				default:
					$where[$fieldarr] = $value;
			}
			$list = db($model)->where($where)->field($key)->select();
			$info = [];
			foreach ($list as $vc) {
				$info[] = $vc[$key];
			}
			if ($info) {
				$whereOr[$tokey] = ['in', implode(',', $info)];
			}
		}
	}
	return $whereOr;
}
// 分析枚举类型配置值 格式 a:名称1,b:名称2
function parse_config_attr($string)
{
	$array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
	if (strpos($string, ':')) {
		$value  =   [];
		foreach ($array as $val) {
			list($k, $v) = explode(':', $val);
			$value[$k]   = $v;
		}
	} else {
		$value  =   $array;
	}
	return $value;
}
function get_avatar($userid)
{
	return  model("Member")->get_member_avatar($userid);
}
function get_nickname($userid)
{
	return  model("Member")->get_member_nickname($userid);
}
function get_realname($userid)
{
	return  model("Member")->get_member_realname($userid);
}
function get_cityname($cityid)
{
	return  model("City")->get_cityname($cityid);
}
function is_mobile()
{
	// returns true if one of the specified mobile browsers is detected
	// 如果监测到是指定的浏览器之一则返回true
	$regex_match = "/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
	$regex_match .= "htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
	$regex_match .= "blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
	$regex_match .= "symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
	$regex_match .= "jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
	$regex_match .= ")/i";
	// preg_match()方法功能为匹配字符，既第二个参数所含字符是否包含第一个参数所含字符，包含则返回1既true
	return preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
}
function send_sms($mobile, $content = '')
{
	$sms = new \base\sms\Sms();
	$data = $sms->send($mobile, $content);
	return $data['status'];
	// return true;
}
function check_sms($mobile, $code)
{
	$sms = new \base\sms\Sms();
	$data = $sms->check($mobile, $code);
	return $data['status'];
	// return true;
}
function get_token($userid, $name, $avatar)
{
	$p = new \base\rongyun\ServerAPI;
	$avatar = $avatar ? $avatar : '/upload/20170512/d3917067b7bd204fa83b0902014ce32e.jpg';
	$p->setConfig(config('RONGYUN_APPKEY'), config('RONGYUN_APPSECRET'));
	$data = $p->getToken($userid, $name, $avatar);
	$data = json_decode($data, true);
	return $data;
}
/**
 * 发送融云系统消息
 * @param  [type]  消息接受用户id   [description]
 * @param  [type]  消息内容   [description]
 * @param  integer 相关文章或信息id [description]
 * @param  [type]  消息类型    [description]
 * @param  [type]  其他用户id  [description]
 * @return [type]             [description]
 */
function send_rongyun_sys_msg($rece_id, $content, $contentid = 0, $typeid = 0, $url = '')
{
	if (!$rece_id) {
		return false;
	}
	$p = new \base\rongyun\ServerAPI;
	$p->setConfig(config('RONGYUN_APPKEY'), config('RONGYUN_APPSECRET'));
	$admininfo = model("Member")->get_data(['item_id' => 1]);
	$uinfo = array(
		'id' => $admininfo['id'],
		'icon' => $admininfo['avatar'],
		'name' => $admininfo['nickname'],
	);
	$r = $p->getToken($admininfo['id'], $admininfo['nickname'], $admininfo['avatar']);
	if ($typeid == 1) {
		$url = "http://coco3g-app/gotopage?url=" . APP_URL . "/index/index/index/id/" . $contentid . "&target=blank&pullrefresh=0&callbackTag=callback_1488956498800&rightBtn=[]";
	}
	$msg = ['content' => trim($content), 'user' => $uinfo, 'extra' => array('url' => $url)];
	if (!is_array($rece_id)) {
		$rece_id = [$rece_id];
	}
	$result = $p->messagePublish($admininfo['id'], $rece_id, 'RC:TxtMsg', json_encode($msg));
	return $result;
}
function send_msg($data)
{
	$p = new \base\rongyun\ServerAPI;
	$p->setConfig(config('RONGYUN_APPKEY'), config('RONGYUN_APPSECRET'));
	$uinfo = array(
		'id' => $data['userid'],
		'icon' => $data['avatar'],
		'name' => $data['name'],
	);
	if (isset($data['content'])) {
		$msg = array('content' => $data['content'], 'user' => $uinfo);
	} else {
		$msg = array('user' => $uinfo);
	}
	$data = $p->messagePublish($data['userid'], $data['touserid'], 'RC:TxtMsg', json_encode($msg));
	return json_decode($data, true);
}
function del_msg()
{
	$p = new \base\rongyun\ServerAPI;
	$p->setConfig(config('RONGYUN_APPKEY'), config('RONGYUN_APPSECRET'));
	$data = $p->messageHistoryDelete('20170407');
	$data = json_decode($data, true);
	return $data;
}
function send_sysmsg($data)
{
	$p = new \base\rongyun\ServerAPI;
	$p->setConfig(config('RONGYUN_APPKEY'), config('RONGYUN_APPSECRET'));
	$uinfo = array(
		'id' => $data['userid'],
		'icon' => $data['avatar'],
		'name' => $data['name'],
	);
	if (isset($data['content'])) {
		$msg = array('content' => $data['content'], 'user' => $uinfo);
	} else {
		$msg = array('user' => $uinfo);
	}
	$data = $p->messageSystemPublish($data['userid'], $data['touserid'], 'RC:TxtMsg', json_encode($msg));
	return json_decode($data, true);
}
// function exec_php($command,$data = [],$status = 1){
// 	$datas = '';
// 	if(!empty($data)){
// 		$datas = '/';
// 	}
// 	foreach($data as $k => $v){
// 		if('' !== trim($v))
// 			$datas .= $k."/".$v."/";
// 	}
// 	$datas = rtrim($datas,"/");
// 	$command .= $datas;
// 	$command_str = "/usr/local/php-5.6/bin/php -c /home/wwwroot/coco/etc/amh-php.ini /home/wwwroot/coco/domain/sijia/web/index.php  ".$command;
// 	if($status){
// 		$command_str .= " > /dev/null &";
// 	}
// 	exec($command_str);
// }
//执行脚本命令
if (!function_exists('exec_php')) {
	function exec_php($command, $data = [], $status = 1)
	{
		$datas = '';
		if (!empty($data)) {
			$datas = '/';
		}
		foreach ($data as $k => $v) {
			if ('' !== trim($v))
				$datas .= $k . "/" . $v . "/";
		}
		$datas = rtrim($datas, "/");
		$command .= $datas;
		if (file_exists('/usr/local/php-5.6')) {
			$command_str = "/usr/local/php-5.6/bin/php -c /home/wwwroot/web/etc/amh-php.ini /home/wwwroot/web/domain/sijiawx/web/index.php " . $command;
		} else {
			$command_str = "/usr/local/php-7.2/bin/php -c /home/wwwroot/web/etc/amh-php.ini /home/wwwroot/web/domain/sijia/web/public/index.php " . $command;
		}

		if ($status) {
			//$command_str .= " > /dev/null &";
		}

		debugLogs($command_str);
		// trace($command_str);
		//exec($command_str, $output);
		exec($command_str . ' 2>&1', $output, $return_val);
		debugLogs($output);
		//file_put_contents($file, print_r($output,true), FILE_APPEND);
	}
}
if (!function_exists('exec_command')) {
	function exec_command($command, $data = [], $status = 1)
	{
		$datas = ' ';
		foreach ($data as $k => $v) {
			if ('' !== trim($v))
				$datas .= "--" . $k . "=" . $v . " ";
		}
		$datas = rtrim($datas, " ");
		$command .= $datas;
		if (file_exists('/usr/local/php-5.6')) {
			$command_str = "/usr/local/php-5.6/bin/php -c /home/wwwroot/web/etc/amh-php.ini /home/wwwroot/web/domain/sijiawx/web/think " . $command;
		} else {
			$command_str = "/usr/local/php-7.2/bin/php -c /home/wwwroot/web/etc/amh-php.ini /home/wwwroot/web/domain/sijia/web/think " . $command;
		}
		if ($status) {
			$command_str .= " > /dev/null &";
		}
		// file_put_contents(ROOT_PATH.'runtime/log/commandstr.log'." \n", $command_str, FILE_APPEND);
		exec($command_str);
	}
}

function debugLogs($content, $file = 'debug.log')
{
	$file = '/home/wwwroot/web/domain/sijiawx/web/logs/' . $file;
	$current = "[" . date('Y-m-d H:i:s') . "] " . print_r($content, true) . "\n";
	file_put_contents($file, $current, FILE_APPEND);
}

//基于数组创建目录和文件
function create_dir_or_files($files)
{
	foreach ($files as $key => $value) {
		if (substr($value, -1) == '/') {
			mkdir($value);
		} else {
			@file_put_contents($value, '');
		}
	}
}
/**
 * http下载文件
 *
 * Reads a file and send a header to force download it.
 * @copyright www.doophp.com
 * @param string $file_str File name with absolute path to it
 * @param bool $isLarge If True, the large file will be read chunk by chunk into the memory.
 * @param string $rename Name to replace the file name that would be downloaded
 */
function download($file, $isLarge = false, $rename = NULL)
{
	if (headers_sent()) return false;
	if (!$file) {
		exit('Error 404:The file not found!');
	}
	if ($rename == NULL) {
		if (strpos($file, '/') === false && strpos($file, '\\') === false)
			$filename = $file;
		else {
			$filename = basename($file);
		}
	} else {
		$filename = $rename;
	}
	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header("Content-Disposition: attachment; filename=\"$filename\"");
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');
	header('Content-Length: ' . filesize($file));
	ob_clean();
	flush();
	if ($isLarge) {
		// self::readfileChunked($file);
	} else {
		readfile($file);
	}
}
//用php从身份证中提取生日,包括15位和18位身份证 
function get_birthday($IDCard)
{
	$result['error'] = 0; //0：未知错误，1：身份证格式错误，2：无错误 
	$result['flag'] = ''; //0标示成年，1标示未成年 
	$result['tdate'] = ''; //生日，格式如：2012-11-15 
	$tdate = '';
	$flag = 0;
	if (!preg_match("/[1-9]([0-9a-zA-Z]{17}|[0-9a-zA-Z]{14})/", $IDCard)) {
		$result['error'] = 1;
		return $result;
	} else {
		if (strlen($IDCard) == 18) {
			$tyear = intval(substr($IDCard, 6, 4));
			$tmonth = intval(substr($IDCard, 10, 2));
			$tday = intval(substr($IDCard, 12, 2));
			if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
				$flag = 0;
			} elseif ($tmonth < 0 || $tmonth > 12) {
				$flag = 0;
			} elseif ($tday < 0 || $tday > 31) {
				$flag = 0;
			} else {
				$tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
				if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
					$flag = 0;
				} else {
					$flag = 1;
				}
			}
		} elseif (strlen($IDCard) == 15) {
			$tyear = intval("19" . substr($IDCard, 6, 2));
			$tmonth = intval(substr($IDCard, 8, 2));
			$tday = intval(substr($IDCard, 10, 2));
			if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
				$flag = 0;
			} elseif ($tmonth < 0 || $tmonth > 12) {
				$flag = 0;
			} elseif ($tday < 0 || $tday > 31) {
				$flag = 0;
			} else {
				$tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
				if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
					$flag = 0;
				} else {
					$flag = 1;
				}
			}
		}
	}
	$result['error'] = 2; //0：未知错误，1：身份证格式错误，2：无错误 
	$result['isAdult'] = $flag; //0标示成年，1标示未成年 
	$result['birthday'] = $tdate; //生日日期 
	return $result;
}
//检验是否收藏
function check_fav($userid, $contentid, $typeid)
{
	return db("Favorites")->where('userid', $userid)->where('contentid', $contentid)->where('typeid', $typeid)->count();
}
//检验是否已评论
function check_evas($userid, $requiresid, $typeid)
{
	return db("Evas")->where('userid', $userid)->where('requiresid', $requiresid)->where('typeid', $typeid)->count();
}
function checkNumberStatus()
{
	$number =  model("Pickorder")->where('userid', $this->uinfo['id'])->where('status', '>', 0)->where('status', '<', 6)->count();
	if ($number > config('YYXZ_NUM')) {
		return '已达到接单数量的上限，不能继续预约';
	}
}
//检查是否可以升级
function check_group($nums, $viplevel)
{
	$level = '';
	foreach ($viplevel as $k => $v) {
		if ($nums >= $v) {
			$level = $k;
		} else {
			break;
		}
	}
	return $level;
}
//检验今天是否点赞
function check_zan($userid, $contentid, $typeid)
{
	return db("Zans")->where('userid', $userid)->where('contentid', $contentid)->where('typeid', $typeid)->whereTime('addtime', 'd')->count();
}
//检验是否点赞
function check_number_zan($userid, $contentid, $typeid)
{
	return db("Zans")->where('userid', $userid)->where('contentid', $contentid)->where('typeid', $typeid)->count();
}
//根据身份证号计算年龄
function getAgeByID($id)
{
	//过了这年的生日才算多了1周岁 
	if (empty($id)) return '';
	$date = strtotime(substr($id, 6, 8));
	//获得出生年月日的时间戳 
	$today = strtotime('today');
	//获得今日的时间戳 111cn.net
	$diff = floor(($today - $date) / 86400 / 365);
	//得到两个日期相差的大体年数 
	//strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比 
	$age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;

	return $age;
}
/**
 * 获取x轴对应的数据，当没有数据时补0
 * @param  array $data 存在的数据
 * @param  array $allx x轴标点
 * @param  string $str $data中字段对应的值的相同部分
 * @return array x轴每个点对应的数据
 */
function get_every($data, $allx, $str = '')
{
	$datas = [];
	$nums = 0;
	foreach ($allx as $v) {
		foreach ($data as $vc) {
			if ($vc['addday'] == $str . $v) {
				$datas[] = $vc['nums'];
				$nums = 1;
				break;
			}
		}
		if ($nums) {
			$nums = 0;
		} else {
			$datas[] = 0;
			$nums = 0;
		}
	}
	return $datas;
}
/*
 des: 将多维数组转换成字符串
   @param: $array 多维数组
   @param: $mode 分割的界定符
   @return: 字符串
*/
function implode_multiArr($array, $mode)
{
	$dataStr = '';

	foreach ($array as $keys => $values) {
		if (is_array($values)) {
			$dataStr .= implode_multiArr($values, $mode);
		} else {
			$dataStr .= $values . $mode;
		}
	}

	return $dataStr;
}
function checkAdminRule($rule, $roleid)
{
	$ruleid = db("Menu")->where("url = '$rule'")->value("id");
	if ($roleid == 1 || $rule == 'index/index' || $rule == 'login/logout' || $rule == 'login/index' || $rule == 'login/login' || strpos($rule, "data_show") !== false) return true;
	$rules = db("AuthGroup")->where("id = '$roleid'")->value("rules");
	// echo $ruleid;
	$rulearr = explode(",", $rules);
	return in_array($ruleid, $rulearr);
}
function createqr($content, $size = 300)
{
	$qrCode = new \base\qrcode\CodeQr;
	return $qrCode->createqr($content, $size);
}
function showqr($content, $size = 300)
{
	$qrCode = new \base\qrcode\CodeQr;
	return $qrCode->showqr($content, $size);
}
function get_charter($string, $type = "head", $blank = '')
{
	$p = new \base\charter\GetCharter;
	return $p->encode($string, $type, $blank);
}
function set_excel($datas = array(), $download = 1, $downdir = '')
{
	think\Loader::import('base.excel.PHPExcel');
	$words = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
	$colums = $datas['colums'];
	Vendor("PHPExcel.PHPExcel");

	$objPHPExcel = new \PHPExcel();
	$objPHPExcel->getProperties()->setCreator($datas['username']);
	$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
	$objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');

	//设置列宽
	for ($i = 0; $i < $colums; $i++) {
		$nowcolum = $words[$i];
		if (isset($datas['colums_width'][$nowcolum]))
			$objPHPExcel->getActiveSheet()->getColumnDimension($nowcolum)->setWidth($datas['colums_width'][$nowcolum]);
		else {
			$objPHPExcel->getActiveSheet()->getColumnDimension($nowcolum)->setAutoSize(true);
		}
	}
	//头
	foreach ($datas['colum_header'] as $k => $v) {
		$ki = $k + 1;
		$nowcolu = $words[$k];
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue($nowcolu . '1', $v);
		$objPHPExcel->getActiveSheet()->getStyle($nowcolu . "1")->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->getStyle($nowcolu . "1")->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle($nowcolu . "1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	}
	$objPHPExcel->getActiveSheet()->getRowDimension("1")->setRowHeight(20);

	foreach ($datas['datalist'] as $ks => $v) {
		$kid = $ks + 2;
		for ($i = 0; $i < $colums; $i++) {
			$nowcolum = $words[$i];
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($nowcolum . $kid, $v[$i]['value']);
			$objPHPExcel->getActiveSheet()->getStyle($nowcolum . $kid)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$objPHPExcel->getActiveSheet()->getStyle($nowcolum . $kid)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
			if (isset($v[$i]['color'])) {
				$objPHPExcel->getActiveSheet()->getStyle($nowcolum . $kid)->getFont()->getColor()->setARGB('FF' . $v[$i]['color']);
			}
		}
	}

	$objPHPExcel->getActiveSheet()->setTitle($datas['title']);
	$objPHPExcel->setActiveSheetIndex(0);
	$filename = $datas['title'];
	$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

	if ($download) {
		$userBrowser = $_SERVER['HTTP_USER_AGENT'];
		if (preg_match('/MSIE/i', $userBrowser)) {
			$filename = urlencode($filename);
		}
		$filename = iconv('UTF-8', 'GBK//IGNORE', $filename);

		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		$objWriter->save('php://output');
		exit;
	} else {
		if (!file_exists(ROOT_PATH . "Application/Runtime/Temp/" . $downdir)) {
			mkdir(ROOT_PATH . "Application/Runtime/Temp/" . $downdir);
		}
		$objWriter->save(ROOT_PATH . "Application/Runtime/Temp/" . $downdir . "/" . $filename . ".xls");
	}
}
